package com.lwl.java8.chapter10;

import org.junit.Test;

import java.util.Optional;
import java.util.Properties;

/**
 * Created by liwenlong on 2017/12/21 10:56 <br/>
 */
public class OptionalTest {

    @Test
    public void test(){

        Optional<Object> empty = Optional.empty();

        Car car = new Car();
        Optional<Car> car1 = Optional.of(car);

        //Optional<Car> optional = Optional.ofNullable(null);
        //Car o1 = optional.get();
        //Optional<Optional<Insurance>> insurance = optional.map(Car::getInsurance);

        Person person = new Person();
        Optional<Person> optPerson = Optional.of(person);

        Optional<Car> car2 = optPerson.flatMap(Person::getCar);
        Optional<Insurance> insurance1 = car2.flatMap(Car::getInsurance);
        Optional<String> str = insurance1.map(Insurance::getName);
        String aaaa = str.orElse("aaaa");
        System.out.println(aaaa);

    }

    public int readDuration(Properties props, String name) {
        return Optional.ofNullable(props.getProperty(name))
                .flatMap(OptionalUtility::strToInteger)
                .filter(i -> i > 0)
                .orElse(0);
    }

    @Test
    public void test2(){
        Properties props = new Properties();
        props.setProperty("a", "5");
        props.setProperty("b", "true");
        props.setProperty("c", "-3");

        System.out.println(readDuration(props,"a"));
        System.out.println(readDuration(props,"b"));
        System.out.println(readDuration(props,"c"));

    }


}
